#include "mouse.h"
#include <system/regs.h>
#include <interrupt/irq.h>
#include <system/mod.h>

module_t mouse_module =
{
	.name = "mouse\0",
	.author = "dak\0",
	.license = "gpl\0",
	.desc = "\0",
	.dep = "\0",
	.type = MOD_TYPE_DEV_HI,
	
	.init = mouse_init,
	.shut = mouse_shut,
};


/*
 * Handler del mouse
 */
static void mouse_callback(regs_t *reg)
{
	mouse_buf.state_data = (uint8_t) io_inb(MOUSE_REG_DATA_READ);
	mouse_buf.x_move = (uint8_t) io_inb(MOUSE_REG_DATA_READ);
	mouse_buf.y_move = (uint8_t) io_inb(MOUSE_REG_DATA_READ);
	
	printf("%d %d\n",mouse_buf.x_move,mouse_buf.y_move);
}



/*
 * Attende che il mouse sia pronto per scrivere su entrambi i registri
 */
uint8_t mouse_wait_write()
{
	char i = io_inb(MOUSE_REG_CMD);
	
	//for bit 1 (value=2) of port 0x64 to become clear
	if((i & (1 << 1)) == 1) return 0;
	return 1;
}


/*
 * Attende che il mouse sia pronto per leggere da 0x60
 */
uint8_t mouse_wait_read()
{
	char i = io_inb(MOUSE_REG_CMD);
	
	//bit 0 (value=1) of port 0x64 is set
	if((i & (1 << 0)) == 1) return 0;
	return 1;
}


/*
 * Invia un commando al chip del mouse
 */
void mouse_cmd(uint8_t cmd, uint8_t data)
{
	io_outb(MOUSE_REG_CMD, 0xD4);
	io_outb(MOUSE_REG_CMD, cmd);	
}


/*
 * Inizializza il mouse
 */
uint32_t mouse_init()
{
	irq_install_handler(IRQ_MOUSE, &mouse_callback);
	
	mouse_cmd(MOUSE_CMD_ENABLE_DATA_REP, 0);
}


/*
 * Deinizializa il mouse
 */
uint32_t mouse_shut()
{
	irq_install_handler(IRQ_MOUSE, NULL);
}


/*
 * Legge i dati dal mouse
 */
uint32_t mouse_read(uint8_t *data, uint32_t size, char *flags)
{
	return 0;
}
